var ws = require('ws').Server;
var EventEmitter = require('events').EventEmitter;
var sessionMgr = require('./sessionmgr');

var curId = 1;

class Connector extends EventEmitter {
	//连接器,管理服务端与客户端的连接
	constructor(port, host, opts) {
		EventEmitter.call(this)
		this.port = port
		this.host = host
		this.opts = opts
		this.routers = {} //路由集合，用于保存注册的消息和对应的方法
		this.wsocket = new ws({
			host: this.host,
			port: this.port
		})
	}

	start(cb) {
		//启动连接
		let self = this
		this.wsocket.on('connection', function(socket) {
			let websocket = new WebSocket(curId++, socket)
			sessionMgr.create(websocket.id, websocket)
			self.emit('connection', websocket);
			self.on('message', function(msg) {
				decode(msg)
			})
		})
		process.nextTick(cb);
	}

	stop(cb) {
		this.wsocket.close()
		process.nextTick(cb);
	}

	encode(reqId, route, msg) {
		//编辑消息
	}

	decode(msg) {
		//解析消息
		msg = JSON.parse(msg)
		let id = msg.id
		let route = msg.route
		let body = msg.body
		let cb = this.routers[route]
		if (cb) {
			cb(body)
		}
	}

	addRoute(route, cb) {
		//注册路由
		if (typeof route === 'string' || typeof cb === 'function') {
			this.routers[route] = cb
		}
	}
}

class WebSocket extends EventEmitter {
	//socket类，封装websocket为Connector提供接口
	constructor(id, socket) {
		EventEmitter.call(this)
		this.id = id
		this.socket = socket
		let self = this
		socket.on('message', function(msg) {
			self.emit('message', msg)
		})
		socket.on('close', function() {
			self.emit('close')
		})
		socket.on("error", function() {
			self.emit('error')
		})
	}

	send(msg) {
		this.socket.send(msg)
	}

	disconnect() {
		this.socket.close()
	}

}
